package com.sparrow.example_message.util;

import io.netty.buffer.ByteBuf;

import java.io.UnsupportedEncodingException;

public class ByteBufUtils {

    public static void writeString(ByteBuf buf, String value) {
        // 为空处理
        if (value == null) {
            // buf.writeInt(0);
            buf.writeInt(0);
            return;
        }
        try {
            byte[] bytes = value.getBytes("UTF-8");
            buf.writeInt(bytes.length);
            buf.writeBytes(bytes);
        } catch (UnsupportedEncodingException e) {
            // LOGGER.error("Encode String Error:" + e.getMessage());
        }
    }


    public static String readString(ByteBuf buf) {
        final int length = buf.readInt();
        if (length <= 0) {
            return null;
        }
        if (buf.readableBytes() < length) {
            return null;
        }
        final byte[] bytes = new byte[length];
        buf.readBytes(bytes);
        try {
            String value = new String(bytes, "UTF-8");
            if ("undefined".equals(value)) {
                return null;
            }
            return value;
        } catch (UnsupportedEncodingException e) {
            // 抛出错误
            e.printStackTrace();
        }
        return null;
    }

}
